;(function(Ext,metaData){
	Ext.Loader.setPath('FormFieldUtil',contextPath+"ui_tpl/FormFieldUtil.js");
	var refMetaMap=metaData["refMetaMap"],
	globalId=id,
	refEnumMap=metaData["refEnumMap"],
	protoMetaId=metaData["meta"],
	protoMeta=refMetaMap[protoMetaId],
	fields=metaData["fields"],
	attrs=metaData["attrs"],
	action=attrs['action']||{type:"rest",url:"/meta/record/"+metaData["id"]},
	modelName="Ext.model."+metaData["code"],
	modelFields=[],columns=[],validators={},
	typeMap={"1":"string","-5":"int","4":"int","12":"string","16":"boolean","91":"date","93":"date","97":"date"};
	Ext.iterate(fields,function(field,i){
		
		var type=field["type"],name=field["name"],f={name:name,type:typeMap[field["type"]]},
		col={dataIndex:name,text:field["text"],menuDisabled:true},
		valid={};
		switch(type){
		case -5:
		case 4:
			break;
		case 91:
			col["renderer"]=Ext.util.Format.dateRenderer('Y-m-d');
			break;
		case 92:
			col["renderer"]=Ext.util.Format.dateRenderer('h:i:s');
			break;
		case 93:
			col["renderer"]=Ext.util.Format.dateRenderer('Y-m-d h:i:s');
			col["width"]=150;
			break;
		}
		modelFields.push(f);
		columns.push(col);
	});
	var startParam ="pageInfo.start",limitParam="pageInfo.limit",pageParam="pageInfo.page",
	sortParam="sortInfo.field",directionParam="sortInfo.direct",
	paramNames={
			startParam:startParam,
			limitParam:limitParam,
			pageParam:pageParam,
			sortParam:sortParam,
			directionParam:directionParam
			},extraParams={};
	extraParams[startParam]= 0;
	extraParams[limitParam]=25;
	extraParams[sortParam]=(attrs.idProperty||"id");
	extraParams[directionParam]="ASC";
	var proxy={
			url:action["url"],
			type:action["type"],
			extraParams: extraParams,
			reader: {  
                type: 'json',
                rootProperty: 'itemList',
                totalProperty: 'pageInfo.total'
            },
            simpleSortMode: true
		};
	Ext.apply(proxy,paramNames);
	Ext.define(modelName,{
		extend:"Ext.data.Model",
		idProperty:attrs["idProperty"]||"id",
		fields:modelFields,
		proxy:proxy
	});
	Ext.define('Ext.ux.GridAttr',{
		extend:'Ext.container.Container',
		xtype:'attrgrid',
		layout:'border',
		requires:[
			'Ext.toolbar.Paging',
			'FormFieldUtil'
		],
		initComponent:function(){
			var me=this,gridCmpId=me["gridCmpId"]="grid"+id,
			attrCmpId=me["attrCmpId"]="attrPanel"+id,
			initConfig=me.initialConfig,
			items=me.items=[];
			me.metaData=metaData;
			Ext.apply(this,attrs);
			this.initDataGrid('center'),
			this.initAttrPanel('east');
			this.items=[];
			this.items.push(this.gridConfig);
			this.items.push(this.attrProps);
			this.callParent();
		},
		
		initGridStore:function(){
			var me=this,store=this.store=Ext.create('Ext.data.Store',{
				model:modelName,
				autoLoad:true,
				sorters:[{
					property:attrs["seqProperty"]||"seq",
					direction:"ASC"
				}]
			});
			var mainProperty=me["parentIdProperty"],seqProperty=me["seqProperty"];
			if(mainProperty&&globalId){
				var proxy = me.store.getProxy(),
			       extraParams= proxy.extraParams;
				extraParams["filter."+me.mainProperty]=globalId;
				if(seqProperty){
					extraParams[sortParam]=seqProperty;
				}
			}
			
			return store;
		},
		initTbar:function(){
			var me=this,tbar=this.tbar=[{
				text:"新增",
				iconCls:"fa fa-plus",
				handler:function(){
					me.showAddNodeWin();
				}
			},{
				text:"编辑",
				iconCls:"fa fa-edit",
				handler:function(){
					me.showEditNodeWin();
				}
			},{
				text:"删除",
				iconCls:"fa fa-remove",
				handler:function(){
					
				}
			},{
				text:"刷新",
				iconCls:'fa fa-refresh',
				handler:function(){
					me.refreshGrid();
				}
			}];
			return tbar;
		},
		
		showAddNodeWin:function(){
			var me=this,moduleId=metaData["id"],attrs=metaData["attrs"],
			idProperty=attrs["idProperty"]||"id",
			typeProperty=attrs["typeProperty"]||"meta",
			winName=this.addNodeWinName="addNodeWin"+moduleId;
			var win=Ext.getCmp(winName);
			if(!win){
				var items=FormFieldUtil.getFormFields(metaData);
				Ext.iterate(items,function(item,i){
					var name=item["name"];
					if(name=="rank"){
						item.value=(moduleId);
						item.hidden=true;
					}else if(name==idProperty){
						item.value=-1;
						item.hidden=true;
					}else if(name=="seq"){
						item.hidden=true;
					}else if(name=="flag"){
						item.value=1;
					}else if(name==me["parentIdProperty"]){
						item.readOnly=true;
					}
				});
				win=new Ext.form.Panel({
					floating:true,
					title:"新增",
					bodyPadding:10,
					url:action["url"],
					closeToolText:"关闭",
					draggable:true,
					modal:true,
					closable:true,
					scrollable:true,
					width:400,
					maxHeight:450,
					defaults:{
						xtype:"textfield",
						width:300
					},
					method:action["method"]||"PUT",
					items:items,
					buttons:[{
						text:'提交',
						formBind:true,
						handler:function(){
							 var win=this.up('form'),form = win.getForm();
					            if (form.isValid()) {
					                form.submit({
					                    success: function(form, action) {
					                    	Ext.toast("新增成功",'提示', 't');
					                    	me.refreshGrid();
					                    	win.hide();
					                    	
					                    },
					                    failure: function(form, action) {
					                    	Ext.toast(action.result.msg,'提示', 't');
					                    	me.refreshGrid();
					                    }
					                });
					            }	
						}
					},{
						text:'取消',
						handler:function(){
							this.up('form').hide();
						}
					}]
				});
			}
			var form=win.getForm(),pfield=form.findField(me.parentIdProperty);
			pfield&&pfield.setValue(globalId);
			Ext.iterate(this.defaultValueMap,function(name,v){
				var f=form.findField(name);
				f&&f.setValue(v);
			});
			win.show();
			
		},
		showEditNodeWin:function(){
			var me=this,attrs=metaData["attrs"];
			var sels=Ext.getCmp(me["gridCmpId"]).getSelection();
			if(sels.length==0)return Ext.toast('请先选择记录');
			var winName=this.editNodeWinName=this.editNodeWinName||("editNodeWin"+moduleId),
			action=attrs["action"]||{},update=attrs["update"]||action;
			var win=Ext.getCmp(winName);
			if(!win){
				var items=FormFieldUtil.getFormFields(metaData),
				moduleId=metaData["id"],
				idProperty=me["idProperty"],
				typeProperty=me["typeProperty"];
				Ext.iterate(items,function(item,i){
					var name=item["name"];
					if(name=="rank"){
						item.value=moduleId;
						item.hidden=true;
					}else if(name=="seq"){
						item.hidden=true;
					}else if(name=="flag"){
						item.value=1;
					}
				});
				win=new Ext.form.Panel({
					floating:true,
					title:"编辑",
					bodyPadding:10,
					url:update["url"]||action["url"],
					closeToolText:"关闭",
					draggable:true,
					closable:true,
					modal:true,
					scrollable:true,
					width:400,
					maxHeight:450,
					defaults:{
						xtype:"textfield",
						width:300
					},
					method:update["method"]||"POST",
					items:items,
					buttons:[{
						text:'提交',
						formBind:true,
						handler:function(){
							 var win=this.up('form'),form = win.getForm();
					            if (form.isValid()) {
					                form.submit({
					                    success: function(form, action) {
					                    	Ext.toast("更新成功",'提示', 't');
					                    	me.refreshGrid();
					                    	win.hide();
					                    	
					                    },
					                    failure: function(form, action) {
					                    	Ext.toast(action.result.msg,'提示', 't');
					                    	me.refreshGrid();
					                    }
					                });
					            }	
						}
					},{
						text:'取消',
						handler:function(){
							this.up('form').hide();
						}
					}]
				});
			}
			var rec=sels[0],data=rec.data;
			if(this.needKeyConvert&&!data.flatten){
				data["flatten"]=true;
				Ext.apply(data,Ext.Object.flatten(data));
			}
			win.getForm().loadRecord(rec);
			win.show();
		},
		refreshGrid:function(){
			this.store.reload();
		},
		initDataGrid:function(region){
			this.initGridStore();
			this.initTbar();
			var me=this,config=this.gridConfig={
				region:region,
				xtype:'grid',
				tbar:me.tbar,
				id:me["gridCmpId"],
				store:me.store,
				columns:columns,
				height:300,
				split:true,
				height:'auto',
				bbar: {
			        xtype: 'pagingtoolbar',
			        displayInfo: true,
			        displayMsg: ' {0} - {1} 总： {2}',
			        emptyMsg: "无数据",
			        store:me.store
			    },
				width:'auto',
				listeners:{
					'itemclick':function( view, record, item, index, e, eOpts ) {
						var fieldId=record.get(me["idProperty"]),attrPanel=Ext.getCmp(me["attrCmpId"]);
						attrPanel.loadRecord(fieldId);
					}
				}
			};
		},
		typeMap:{
			"-5":"number",
			"4":"number",
			"1":"string",
			"12":"string",
			"91":"date",
			"92":"date",
			"93":"date",
			"16":"boolean"
		},
		initAttrPanel:function(region){
			var me=this,
			attrMeta=attrs["meta"],
			attrMetaModelId=attrMeta["trait"]["attr"]*1,
			attrMetaModel=refMetaMap[attrMetaModelId],
			attrConfigFields=attrMetaModel["fields"],
			propattrs=attrMetaModel["attrs"],
			url=contextPath+"meta/singleRecord/"+attrMetaModelId,
			submitUrl=contextPath+"meta/record/"+attrMetaModelId;
			var sourceConfig={},source={},rawSource={},action=propattrs["action"]||{};
			Ext.iterate(attrConfigFields,function(field,i){
				var name=field["name"];
				sourceConfig[name]={
						displayName:field["text"],
						type:me["typeMap"][field["type"]]
				}
				source[name]="";
			});
			Ext.apply(rawSource,source);
			var config=this.attrProps={
					xtype:'propertygrid',
					region:region,
					id:me["attrCmpId"],
					split:true,
					width:400,
					source:source,
					tbar:[{
						text:"提交",
						iconCls:"fa fa-save",
						handler:function(){
							var props=this.up('propertygrid'),
							originalSource=props["originalSource"],
							source=props.getSource(),rs={};
							Ext.iterate(source,function(k,v){
								var ov=originalSource[k];
								console.log(k);
								if(ov!=v){
									rs[k]=v;
								}
							});
							if(Ext.isEmpty(rs)){
								return Ext.toast('没有修改,无需提交','提示');
							}
							var grid=Ext.getCmp(me["gridCmpId"]),
							sels=grid.getSelection();
							if(sels.length==0)return;
							var sel=sels[0],id=sel.get("id");
							rs["id"]=id;
							Ext.Ajax.request({
								url:submitUrl,
								method:"POST",
								params:rs,
								success: function(response, opts) {
							         var obj = Ext.decode(response.responseText);
							         if(obj["success"]){
							        	 me["originalSource"]=source;
							        	 Ext.toast('保存成功','提示');
							         }else{
							        	 Ext.toast('更新失败','提示');
							         }
							     },

							     failure: function(response, opts) {
							    	 Ext.toast('更新失败','提示');
							     }
							});
						}},{
							text:"刷新",
							iconCls:"fa fa-refresh",
							handler:function(){
								var grid=Ext.getCmp(me["gridCmpId"]),
								sels=grid.getSelection();
								if(sels.length==0)return;
								var sel=sels[0],id=sel.get("id");
								this.up('propertygrid').loadRecord(id);
							}
						}
					],
					sourceConfig:sourceConfig,
					
			};
			config["loadRecord"]=function(id){
				var me=this;
				Ext.Ajax.request({
					url:url,
					method:"GET",
					params:{
						id:id
					},
					success: function(response, opts) {
				         var obj = Ext.decode(response.responseText);
				         if(obj["success"]){
				        	 var data=obj["data"];
				        	 Ext.applyIf(data,rawSource);
				        	 me.setSource(data);
				        	 me["originalSource"]={};
				        	 Ext.apply(me["originalSource"],data);
				         }else{
				        	 me.setSource(rawSource);
				        	 Ext.toast('数据加载失败','提示');
				         }
				     },

				     failure: function(response, opts) {
				    	 me.setSource(rawSource);
				    	 Ext.toast('数据加载失败','提示');
				     }
				});
			};
		}
	});
	Ext.application({
	    name: 'MyApp',
	    mainView:'Ext.ux.GridAttr',
	    launch: function () {
	    }
	});
})(Ext,metaData);

